package cn.shenlong.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class StrUtils {
	/**
	 * 去除字符串中的空格、回车、换行符、制表符
	 * 
	 * @param str
	 * @return
	 */
	public static String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}

	/**
	 * 字符转Date类型
	 * 
	 * @param str
	 * @return
	 */
	public static Date stringToDate(String str) {
		Date date = null;
		if (str != null) {
			DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			try {
				date = sdf.parse(str);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return date;
	}

	/**
	 * 正则表达式判断手机号
	 * 
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	/**
	 * 根据地址,获取经纬度
	 * 
	 * @param addr
	 * @return
	 */
	public static String[] getCoordinate(String addr) {
		String address = null;
		try {
			address = java.net.URLEncoder.encode(addr, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		;
		String output = "csv";
		String key = "AIzaSyBlzYLu2KlOxthz0mYupByFGJyGpPZBgkk&hl";
		String url = String.format(
				"http://maps.google.com/maps/geo?q=%s&output=%s&key=%s",
				address, output, key);
		URL myURL = null;
		URLConnection httpsConn = null;
		// 进行转码
		try {
			myURL = new URL(url);
		} catch (MalformedURLException e) {

		}
		try {
			httpsConn = (URLConnection) myURL.openConnection();
			if (httpsConn != null) {
				InputStreamReader insr = new InputStreamReader(
						httpsConn.getInputStream(), "UTF-8");
				BufferedReader br = new BufferedReader(insr);
				String data = null;
				if ((data = br.readLine()) != null) {
					String[] retList = data.split(",");

					return retList;
				}
				insr.close();
			}
		} catch (IOException e) {

		}
		return null;
	}

	/**
	 * 根据地址,获取经纬度
	 * 
	 * @param addr
	 * @return
	 */
	public static Map<String, Object> getCoordinate2(String addr) {
		String address = null;
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			address = java.net.URLEncoder.encode(addr, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		String key = "f247cdb592eb43ebac6ccd27f796e2d2";
		String url = String
				.format("http://api.map.baidu.com/geocoder?address=%s&output=json&key=%s",
						address, key);
		URL myURL = null;
		URLConnection httpsConn = null;
		try {
			myURL = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		try {
			httpsConn = (URLConnection) myURL.openConnection();// 不使用代理
			if (httpsConn != null) {
				InputStreamReader insr = new InputStreamReader(
						httpsConn.getInputStream(), "UTF-8");
				BufferedReader br = new BufferedReader(insr);
				String data = null;
				StringBuffer resultBuffer = new StringBuffer();
				while ((data = br.readLine()) != null) {
					resultBuffer.append(data);
				}
				JSONObject json = JSONObject
						.fromObject(resultBuffer.toString());
				String status = json.getString("status");
				if (status != null && "OK".equals(status)) {
					String resultStr = json.getString("result");
					if (resultStr != null && !"".equals(resultStr)
							&& !"[]".equals(resultStr)) {
						JSONObject resultJson = (JSONObject) json.get("result");
						String locationStr = resultJson.getString("location");
						JSONObject locationJson = JSONObject
								.fromObject(locationStr);
						map.put("lng", locationJson.getString("lng"));
						map.put("lat", locationJson.getString("lat"));
					}
				}
				// JsonReader reader = new JsonReader(insr);
				// reader.beginObject();
				// while (reader.hasNext()) {
				// String tagName = reader.nextName();
				// if (tagName.equals("result")) {
				// reader.beginObject();
				// List<Map<String, String>> list = new ArrayList<Map<String,
				// String>>();
				// while (reader.hasNext()) {
				// Map<String, String> map_temp = new HashMap<String, String>();
				// tagName = reader.nextName();
				// if (tagName.equals("location")) {
				// reader.beginObject();
				// while (reader.hasNext()) {
				// map_temp.put(reader.nextName(),
				// reader.nextString());
				// }
				// reader.endObject();
				// } else if(tagName.equals("precise")) {
				// map_temp.put("precise", reader.nextString());
				// }
				// list.add(map_temp);
				// }
				// map.put("result", list);
				// reader.endObject();
				// } else if (tagName.equals("status")) {
				// map.put("status", reader.nextString());
				// }
				// }
				// insr.close();
				// }
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return map;
	}

	public void getCoordinate(String longitude, String latitude) {
		String url = String
				.format("http://api.map.baidu.com/geocoder?output=json&"
						+ "location=%s,%s%s&key=f247cdb592eb43ebac6ccd27f796e2d2",
						latitude, "%20", longitude);
		URL myURL = null;
		URLConnection httpsConn = null;
		try {
			myURL = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		try {
			httpsConn = (URLConnection) myURL.openConnection();
			if (httpsConn != null) {
				InputStreamReader insr = new InputStreamReader(
						httpsConn.getInputStream(), "UTF-8");
				BufferedReader br = new BufferedReader(insr);
				String data = null;
				while ((data = br.readLine()) != null) {
					System.out.println(data);
				}
				insr.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取随机生成的4位数字(0~9)
	 * 
	 * @return
	 */
	public static String getRandomNum() {
		String str = "";
		Random random = new Random();
		for (int i = 0; i < 4; i++) {
			int itmp = random.nextInt(10);
			str += itmp;
		}
		return str;
	}

	/**
	 * 处理url
	 * 
	 * url为null返回null，url为空串或以http://或https://开头，则加上http://，其他情况返回原参数。
	 * 
	 * @param url
	 * @return
	 */
	public static String handelUrl(String url) {
		if (url == null) {
			return null;
		}
		url = url.trim();
		if (url.equals("") || url.startsWith("http://")
				|| url.startsWith("https://")) {
			return url;
		} else {
			return "http://" + url.trim();
		}
	}

	/**
	 * 分割并且去除空格
	 * 
	 * @param str
	 *            待分割字符串
	 * @param sep
	 *            分割符
	 * @param sep2
	 *            第二个分隔符
	 * @return 如果str为空，则返回null。
	 */
	public static String[] splitAndTrim(String str, String sep, String sep2) {
		if (StringUtils.isBlank(str)) {
			return null;
		}
		if (!StringUtils.isBlank(sep2)) {
			str = StringUtils.replace(str, sep2, sep);
		}
		String[] arr = StringUtils.split(str, sep);
		// trim
		for (int i = 0, len = arr.length; i < len; i++) {
			arr[i] = arr[i].trim();
		}
		return arr;
	}

	/**
	 * 文本转html
	 * 
	 * @param txt
	 * @return
	 */
	public static String txt2htm(String txt) {
		if (StringUtils.isBlank(txt)) {
			return txt;
		}
		StringBuilder sb = new StringBuilder((int) (txt.length() * 1.2));
		char c;
		boolean doub = false;
		for (int i = 0; i < txt.length(); i++) {
			c = txt.charAt(i);
			if (c == ' ') {
				if (doub) {
					sb.append(' ');
					doub = false;
				} else {
					sb.append("&nbsp;");
					doub = true;
				}
			} else {
				doub = false;
				switch (c) {
				case '&':
					sb.append("&amp;");
					break;
				case '<':
					sb.append("&lt;");
					break;
				case '>':
					sb.append("&gt;");
					break;
				case '"':
					sb.append("&quot;");
					break;
				case '\n':
					sb.append("<br/>");
					break;
				default:
					sb.append(c);
					break;
				}
			}
		}
		return sb.toString();
	}

	/**
	 * 剪切文本。如果进行了剪切，则在文本后加上"..."
	 * 
	 * @param s
	 *            剪切对象。
	 * @param len
	 *            编码小于256的作为一个字符，大于256的作为两个字符。
	 * @return
	 */
	public static String textCut(String s, int len, String append) {
		if (s == null) {
			return null;
		}
		int slen = s.length();
		if (slen <= len) {
			return s;
		}
		// 最大计数（如果全是英文）
		int maxCount = len * 2;
		int count = 0;
		int i = 0;
		for (; count < maxCount && i < slen; i++) {
			if (s.codePointAt(i) < 256) {
				count++;
			} else {
				count += 2;
			}
		}
		if (i < slen) {
			if (count > maxCount) {
				i--;
			}
			if (!StringUtils.isBlank(append)) {
				if (s.codePointAt(i - 1) < 256) {
					i -= 2;
				} else {
					i--;
				}
				return s.substring(0, i) + append;
			} else {
				return s.substring(0, i);
			}
		} else {
			return s;
		}
	}

	/**
	 * 检查字符串中是否包含被搜索的字符串。被搜索的字符串可以使用通配符'*'。
	 * 
	 * @param str
	 * @param search
	 * @return
	 */
	public static boolean contains(String str, String search) {
		if (StringUtils.isBlank(str) || StringUtils.isBlank(search)) {
			return false;
		}
		String reg = StringUtils.replace(search, "*", ".*");
		Pattern p = Pattern.compile(reg);
		return p.matcher(str).matches();
	}

	/**
	 * 使用fck上传图片后，入库时，处理图片地址。 例如：
	 * 数据库取出的原始地址：http://img.fjsq.org//cms/common/2013
	 * /03/18/cms-common-204c95f96a384420bc06cf5d3a704559.jpg
	 * 处理后的地址：/cms/common/
	 * 2013/03/18/cms-common-204c95f96a384420bc06cf5d3a704559.jpg
	 * 
	 * @param str
	 * @param fileDomain
	 * @return
	 */
	public static String subfckImageUrl(String str, String fileDomain) {
		String result = "";
		if (str != null && !"".equals(str)) {
			Document doc = Jsoup.parse(str);
			Elements imgs = doc.getElementsByTag("img");
			for (Element img : imgs) {
				String linksHref = img.attr("src");
				linksHref = linksHref.substring(
						linksHref.indexOf("http://") + 7, linksHref.length());
				linksHref = linksHref.substring(linksHref.indexOf("/"),
						linksHref.length());
				img.attr("src", linksHref);
			}
			result = doc.toString();
		}
		return result;
	}

	/**
	 * 使用fck上传图片后，展示图片时，处理图片地址。 例如：
	 * 数据库取出的原始地址：/cms/common/2013/03/18/cms-common-
	 * 204c95f96a384420bc06cf5d3a704559.jpg
	 * 处理后的地址：http://img.fjsq.org//cms/common
	 * /2013/03/18/cms-common-204c95f96a384420bc06cf5d3a704559.jpg
	 * 
	 * @param str
	 * @param fileDomain
	 * @return
	 */
	public static String addfckImageUrl(String str, String fileDomain) {
		String result = "";
		if (str != null && !"".equals(str)) {
			Document doc = Jsoup.parse(str);
			Elements imgs = doc.getElementsByTag("img");
			for (Element img : imgs) {
				String linksHref = img.attr("src");
				StringBuffer sb = new StringBuffer();
				sb.append(fileDomain).append("/");
				sb.append(linksHref);
				img.attr("src", sb.toString());
			}
			result = doc.toString();
		}
		return result;
	}

	/**
	 * 获取html标签中的文字信息
	 * 
	 * @param str
	 * @return
	 */
	public static String htmlToText(String str) {
		String result = "";
		if (str != null && !"".equals(str)) {
			Document doc = Jsoup.parse(str);
			result = doc.text();
		}
		return result;
	}

	/**
	 * 字符串替换函数
	 * 
	 * @param from
	 *            要替换的字符
	 * @param to
	 *            要替换成的目标字符
	 * @param source
	 *            要替换的字符串
	 * @return 替换后的字符串
	 */
	public static String str_replace(String from, String to, String source) {
		StringBuffer bf = new StringBuffer("");
		StringTokenizer st = new StringTokenizer(source, from, true);
		while (st.hasMoreTokens()) {
			String tmp = st.nextToken();
			if (from.indexOf(tmp) >= 0) {
				bf.append(to);
			} else {
				bf.append(tmp);
			}
		}
		return bf.toString();
	}

	/**
	 * 给字符串新增html src属性
	 * 
	 * @param str
	 * @param fileDomain
	 * @return
	 */
	public static String strAddImg(String str, String fileDomain) {
		String result = "";
		if (str != null && !"".equals(str)) {
			StringBuffer buffer = new StringBuffer();
			buffer.append("<img src='").append(fileDomain).append(str);
			buffer.append("' width='400px' height='420px'/>");
			buffer.append("</br>");
			result = buffer.toString();
		}
		return result;
	}

	/**
	 * 去除字符串数组中的空值
	 * 
	 * @param data
	 * @return
	 */
	public static String[] replaceString(String[] data) {
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < data.length && data.length > 0; i++) {
			if (data[i] == null || "".equals(data[i].trim().toString())) {
				continue;
			} else {
				list.add(data[i]);
			}
		}
		String[] newArray = new String[list.size()];
		for (int i = 0; i < newArray.length; i++) {
			newArray[i] = list.get(i);
		}
		return newArray;
	}
}
